package ren.kane.phoenix.juc;

import java.util.concurrent.CyclicBarrier;

/**
 * @author renrk(1275) on 2019-08-20 10:07 AM
 **/
public class CyclicBarrierDemo {
    public static void main(String[] args) throws Exception {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3,
            new Thread(() -> System.out.println(Thread.currentThread().getName() + " barrier action"), "barrierAction"));
        CyclicBarrierThread t1 = new CyclicBarrierThread("t1", cyclicBarrier);
        CyclicBarrierThread t2 = new CyclicBarrierThread("t2", cyclicBarrier);
        t1.start();
        t2.start();
        System.out.println(Thread.currentThread().getName() + " going to await");
        cyclicBarrier.await();
        System.out.println(Thread.currentThread().getName() + " continue");
    }
}

class CyclicBarrierThread extends Thread {
    private CyclicBarrier cyclicBarrier;

    public CyclicBarrierThread(String name, CyclicBarrier cyclicBarrier) {
        super(name);
        this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " going to await");
        try {
            cyclicBarrier.await();
            System.out.println(Thread.currentThread().getName() + " continue");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}